package com.example.emergencyattempt01.fragement.user_fragment;

import android.app.AlertDialog;
import android.app.Fragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.emergencyattempt01.R;
import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.Pack_DePackUtil;
import com.example.emergencyattempt01.activity.utils.ServerMessage;
import com.example.emergencyattempt01.adapter.AllTypeDialog_ListViewAdapter;
import com.example.emergencyattempt01.adapter.St_BookAdapter;
import com.example.emergencyattempt01.user.Student;
import com.example.emergencyattempt01.user.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Borrow_Book_Fragment extends Fragment {
    // 基本控件
    SwipeRefreshLayout stBookRefresher;
    TextView searchTypeField;
    EditText searchField;
    ImageView moreOption;
    ListView bookListView;
    List<Map<String,Object>> bookList=new ArrayList<>();
    St_BookAdapter bookAdapter;
    TextView itemNumber;

    AlertDialog typeDialog;


    Handler handlerForBookBorrow=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int number=bookList.size();
            String display="共包含"+number+"条记录";
            switch (msg.what)
            {
                case  LOAD_ALL_BOOK_SUCCESS:
                    bookAdapter.notifyDataSetChanged();
                    itemNumber.setText(display);
                    break;
                case LOAD_ALL_BOOK_NOT_FOUND:
                    bookAdapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(),"未找到任何记录",Toast.LENGTH_SHORT).show();
                    itemNumber.setText("未找到任何记录");
                    break;
                case LOAD_ALL_BOOK_FAIL:
                    Toast.makeText(getActivity(),"加载失败",Toast.LENGTH_SHORT).show();
                    itemNumber.setText("服务器走神ing...");
                    break;
                case REFRESH_SUCCESS:
                    bookAdapter.notifyDataSetChanged();
                    itemNumber.setText(display);
                    stBookRefresher.setRefreshing(false);
                    break;
                case REFRESH_NOT_FOUND:
                    bookAdapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(),"未找到任何记录",Toast.LENGTH_SHORT).show();
                    itemNumber.setText("未找到任何记录");
                    stBookRefresher.setRefreshing(false);
                    break;
                case REFRESH_FAIL:
                    Toast.makeText(getActivity(),"刷新失败",Toast.LENGTH_SHORT).show();
                    itemNumber.setText("服务器走神ing...");
                    stBookRefresher.setRefreshing(false);
                    break;
                case SEARCH_BOOK_SUCCESS:
                    bookAdapter.notifyDataSetChanged();
                    itemNumber.setText(display);
                    break;
                case SEARCH_BOOK_NOT_FOUND:
                    bookAdapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(),"未找到任何记录",Toast.LENGTH_SHORT).show();
                    itemNumber.setText("未找到任何记录");
                    break;
                case SEARCH_BOOK_FAIL:
                    Toast.makeText(getActivity(),"查找失败",Toast.LENGTH_SHORT).show();
                    itemNumber.setText("服务器走神ing...");
                    break;
            }
        }
    };

    final int LOAD_ALL_BOOK_SUCCESS=0x025;
    final int LOAD_ALL_BOOK_NOT_FOUND=0x026;
    final int LOAD_ALL_BOOK_FAIL=0x027;
    final int REFRESH_SUCCESS=0x028;
    final int REFRESH_NOT_FOUND=0x029;
    final int REFRESH_FAIL=0x030;
    final int SEARCH_BOOK_SUCCESS=0x031;
    final int SEARCH_BOOK_NOT_FOUND=0x032;
    final int SEARCH_BOOK_FAIL=0x033;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.borrow_book_fragment_layout,null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initUser();
        initPage();
        // 设置加载
        setLoad();
        // 设置刷新
        setRefresh();
        // 设置搜索
        setSearch();
        // 设置搜索类型
        setSearchType();
        // 设置展示所有类型
        setMoreOption();
    }

    private void setMoreOption() {
        moreOption.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
                final View view=LayoutInflater.from(getActivity()).inflate(R.layout.all_type_dailog_layout,null);
                builder.setView(view);
                ListView dialogListView=view.findViewById(R.id.all_type_listView);
                final List<String> types=new ArrayList<>();
                final AllTypeDialog_ListViewAdapter adapter=new AllTypeDialog_ListViewAdapter(view.getContext(),types);
                dialogListView.setAdapter(adapter);

                final Handler handler=new Handler()
                {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        if(msg.what==1)
                        {
                            adapter.notifyDataSetChanged();
                        }
                        else {
                            Toast.makeText(view.getContext(),"网络异常",Toast.LENGTH_SHORT).show();
                        }
                    }
                };

                new Thread()
                {
                    @Override
                    public void run() {
                        try {
                            ServerMessage serverMessage=NetWorkUtils.getInstance().create(null,"/find_all_type");
                            int code=serverMessage.getRespondCode();
                            if(code==200)
                            {
                                String fromServer=(String)serverMessage.getFromServer();
                                JSONArray jsonArray=new JSONArray(fromServer);
                                for(int i=0;i<jsonArray.length();i++)
                                {
                                    types.add(jsonArray.getJSONObject(i).getString("type"));
                                }
                                Message message=new Message();
                                message.what=1;
                                handler.sendMessage(message);

                            }
                            else
                            {
                                Message message=new Message();
                                message.what=0;
                                handler.sendMessage(message);
                            }

                        }catch (JSONException e){e.printStackTrace();}
                        catch (IOException e){e.printStackTrace();
                            Message message=new Message();
                            message.what=0;
                            handler.sendMessage(message);}
                    }
                }.start();

                AlertDialog dialog=builder.create();
                dialog.show();
                dialog.getWindow().setLayout(600,800);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
        });
    }

    private void setSearchType() {
        searchTypeField.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
                View view=LayoutInflater.from(getActivity()).inflate(R.layout.book_search_rule,null);
                builder.setView(view);
                TextView bookNameField=view.findViewById(R.id.search_type_bookName);
                TextView pressField=view.findViewById(R.id.search_type_press);
                TextView authorField=view.findViewById(R.id.search_type_author);
                TextView typeField=view.findViewById(R.id.search_type_type);

                bookNameField.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchTypeField.setText("书名");
                        typeDialog.dismiss();
                    }
                });

                pressField.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchTypeField.setText("出版社");
                        typeDialog.dismiss();
                    }
                });

                typeField.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchTypeField.setText("分类");
                        typeDialog.dismiss();
                    }
                });

                authorField.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchTypeField.setText("作者");
                        typeDialog.dismiss();
                    }
                });
                typeDialog=builder.create();
                typeDialog.show();
                typeDialog.getWindow().setLayout(700,800);
            }
        });
    }

    private void setSearch() {
        searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId== EditorInfo.IME_ACTION_SEARCH)
                {
                    new Thread()
                    {
                        @Override
                        public void run() {
                            try
                            {
                                String keyWord=searchField.getText().toString().trim();
                                String type=searchTypeField.getText().toString();
                                if(keyWord.equals(""))// 不许输入空
                                {
                                    Toast.makeText(getActivity(),"不许输入为空！",Toast.LENGTH_SHORT).show();
                                }
                                else
                                {
                                    JSONObject jsonObject=new JSONObject();
                                    jsonObject.put("keyWord",keyWord);
                                    jsonObject.put("searchType",type);
                                    String toServe=String.valueOf(jsonObject);
                                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServe,"/search_by_keyword");
                                    int code=serverMessage.getRespondCode();
                                    if(code==200)
                                    {
                                        String fromServer=(String) serverMessage.getFromServer();
                                        if(Pack_DePackUtil.dePackBookWithCheck(fromServer,bookList))// 找到了
                                        {
                                            Message message=new Message();
                                            message.what=SEARCH_BOOK_SUCCESS;
                                           handlerForBookBorrow.sendMessage(message);
                                        }
                                        else// 没找到
                                        {
                                            Message message=new Message();
                                            message.what=SEARCH_BOOK_NOT_FOUND;
                                            handlerForBookBorrow.sendMessage(message);
                                        }
                                    }
                                    else {
                                        Message message=new Message();
                                        message.what=SEARCH_BOOK_FAIL;
                                        handlerForBookBorrow.sendMessage(message);
                                    }
                                }
                            }catch (JSONException e){e.printStackTrace();}
                            catch (IOException e){e.printStackTrace();
                                Message message=new Message();
                                message.what=SEARCH_BOOK_FAIL;
                                handlerForBookBorrow.sendMessage(message);}
                        }
                    }.start();
                }
                return false;
            }
        });
    }

    private void setRefresh() {
        stBookRefresher.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread()
                {
                    @Override
                    public void run() {
                        try {
                            ServerMessage serverMessage=NetWorkUtils.getInstance().create(null,"/search_all_book");
                            int code=serverMessage.getRespondCode();
                            if(code==200)
                            {
                                String fromServer=(String) serverMessage.getFromServer();
                                if(Pack_DePackUtil.dePackBookWithCheck(fromServer,bookList))// 找到了
                                {
                                    Message message=new Message();
                                    message.what=REFRESH_SUCCESS;
                                    handlerForBookBorrow.sendMessage(message);
                                }
                                else // 没找到
                                {
                                    Message message=new Message();
                                    message.what=REFRESH_NOT_FOUND;
                                    handlerForBookBorrow.sendMessage(message);
                                }
                            }
                            else
                            {
                                Message message=new Message();
                                message.what=REFRESH_FAIL;
                                handlerForBookBorrow.sendMessage(message);
                            }
                        }catch (JSONException e){e.printStackTrace();}
                        catch (IOException e){e.printStackTrace();
                            Message message=new Message();
                            message.what=REFRESH_FAIL;
                            handlerForBookBorrow.sendMessage(message);}
                    }
                }.start();
            }
        });
    }

    private void setLoad() {
        new Thread()
        {
            @Override
            public void run() {
                try {
                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(null,"/search_all_book");
                    int code=serverMessage.getRespondCode();
                    if(code==200)
                    {
                        String fromServer=(String) serverMessage.getFromServer();
                        if(Pack_DePackUtil.dePackBookWithCheck(fromServer,bookList))// 找到了
                        {
                            Message message=new Message();
                            message.what=LOAD_ALL_BOOK_SUCCESS;
                            handlerForBookBorrow.sendMessage(message);
                        }
                        else // 没找到
                        {
                            Message message=new Message();
                            message.what=LOAD_ALL_BOOK_NOT_FOUND;
                            handlerForBookBorrow.sendMessage(message);
                        }
                    }
                    else
                    {

                        Message message=new Message();
                        message.what=LOAD_ALL_BOOK_FAIL;
                        handlerForBookBorrow.sendMessage(message);
                    }
                }catch (JSONException e){e.printStackTrace();}
                catch (IOException e){e.printStackTrace();
                    Message message=new Message();
                    message.what=LOAD_ALL_BOOK_FAIL;
                    handlerForBookBorrow.sendMessage(message);}
            }
        }.start();
    }

    private void initPage() {
        stBookRefresher=getActivity().findViewById(R.id.st_book_refresh);
        searchField=getActivity().findViewById(R.id.borrow_book_search_edit);
        searchTypeField=getActivity().findViewById(R.id.borrow_book_search_type);
        moreOption=getActivity().findViewById(R.id.borrow_book_more_info);
        bookListView=getActivity().findViewById(R.id.borrow_book_search_listView);
        itemNumber=getActivity().findViewById(R.id.borrow_book_itemNumber);
        bookAdapter=new St_BookAdapter(getActivity(),bookList,Student.getInstance());
        bookListView.setAdapter(bookAdapter);
    }

    private void initUser() {
        User student=Student.getInstance();
        Student.initUser(getActivity(),student);// 写完登录之后，可以修改User为一个抽象类，然后提取共同的方法，进行改造
    }
}
